package com.sti.platform.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aisino.core.common.JsonPost;
import com.aisino.core.controller.BaseController;
import com.aisino.tools.util.WebConstants;
import com.sti.platform.model.Group;
import com.sti.platform.model.User;
import com.sti.platform.service.GroupService;
import com.sti.platform.service.UserService;

@Controller
@RequestMapping("group")
public class GroupController extends BaseController{
	@Autowired
	private GroupService groupService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("list")
	public String queryList(HttpServletRequest request,String params,Integer index,Integer row){
		List<Group> list = groupService.queryList(params, index, row);
		request.setAttribute("list", list);
		return "user/group";
	}
	
	@RequestMapping("addHtml")
	public String addHtml(HttpServletRequest request){
		List<User> list = userService.queryUsersByCondition(null, null, null);
		request.setAttribute("list", list);
		return "user/add_group";
	}
	
	@RequestMapping("addGroup")
	public @ResponseBody Map addGroup(final Group group,final String userIds){
		return super.jsonPost(new JsonPost(){
			public void doInstancePost(Map map){
				groupService.addGroup(group,userIds);
			}
		});
	}
	
	@RequestMapping("delectGroup")
	public @ResponseBody Map delect(final String groupId){
		return super.jsonPost(new JsonPost(){
			public void doInstancePost(Map map){
				groupService.delectGroup(groupId);
			}
		});
	}
	
	@RequestMapping("delectGroups")
	public @ResponseBody Map delects(final String groupIds){
		return super.jsonPost(new JsonPost(){
			public void doInstancePost(Map map){
				groupService.delectGroups(groupIds);
			}
		});
	}
	
	@RequestMapping("editor")
	public String editorGroup(HttpServletRequest request){
		String groupId = request.getParameter("groupId");
		/**
		 * ①查询用户组信息
		 * ②查询绑定的用户列表
		 * ③查询所有的用户信息（校验是否已选中）
		 */
		Group group = groupService.queryGroup(groupId);
		List<User> list = groupService.queryUser(groupId);
		List<User> users = groupService.queryUsers(groupId);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("group", group);
		map.put("list", list);
		map.put("users", users);
		request.setAttribute("map", map);
		return "user/editor_group";
	}
	
	@RequestMapping("queryUser")
	public @ResponseBody Map queryUser(final String userIds){
		final List<String> list = Arrays.asList(userIds.split(","));
		return super.jsonPost(new JsonPost(){
			public void doInstancePost(Map map){
				map.put(WebConstants.JSON_MESSAGE, userService.queryUserList(list));;
			}
		});
	}
	
}
